#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''

from com.zxy.adminlog.UsAdmin_Log import UsAdmin_Log
from com.zxy.common import Com_Para
from com.zxy.common.Com_Fun import Com_Fun
import paho.mqtt.client as mqtt
import importlib
from com.zxy.z_debug import z_debug
class MqttThread(z_debug):
    def __init__(self):
        pass
    def run(self):        
        if Com_Para.mqclient is None or not Com_Para.mqclient.is_connected():
            Com_Para.mqclient = mqtt.Client(client_id="zxy_mqtt_client",clean_session=True, transport="tcp")
            Com_Para.mqclient._username = Com_Para.MQTT_username
            Com_Para.mqclient._password =Com_Para.MQTT_pwd            
            Com_Para.mqclient.on_connect = self.on_connect
            Com_Para.mqclient.on_message = self.on_message    
            try:
                Com_Para.mqclient.connect(Com_Para.MQTT_host.split(":")[0],port=int(Com_Para.MQTT_host.split(":")[1]))
                Com_Para.mqclient.loop_start()
            except Exception as e:
                if str(type(self)) == "<class 'type'>":
                    self.debug_in(self,repr(e))#打印异常信息
                else:
                    self.debug_in(repr(e))#打印异常信息
    def on_connect(self,client, userdata, flags, rc):
        for strtopic in Com_Para.MQTT_topic_get.split(","):
            client.subscribe(strtopic)  
    def on_message(self,client, userdata, msg):
        inputStrResult = msg.payload.decode(Com_Para.U_CODE)
        if Com_Para.MQTTREFLECT_IN_CLASS != "":
            try:
                objC = importlib.import_module(Com_Para.MQTTREFLECT_IN_CLASS)  #对模块进行导入                
                objName = Com_Para.MQTTREFLECT_IN_CLASS.split(".")
                objN = getattr(objC,objName[len(objName) - 1])
                if hasattr(objN,"strResult"):
                    setattr(objN,"strResult",inputStrResult)
                    setattr(objN,"strIP","0.0.0.0")
                    fun_us = getattr(objN,"init_start")
                    fun_us(objN)
            except Exception as e:
                if str(type(self)) == "<class 'type'>":
                    self.debug_in(self,Com_Para.MQTTREFLECT_IN_CLASS+"==>"+repr(e))#打印异常信息
                else:
                    self.debug_in(Com_Para.MQTTREFLECT_IN_CLASS+"==>"+repr(e))#打印异常信息
            finally:
                pass